package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /*
    *新增菜品
    * */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /*
    * 菜品的分页查询
    * */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        //分页构造器
        Page<Dish> pageinfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        //过滤条件
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //排序条件
        qw.orderByDesc(Dish::getUpdateTime);
        //分页查询
        Page<Dish> dishPage = dishService.page(pageinfo, qw);
        //对象拷贝
        BeanUtils.copyProperties(pageinfo,dishDtoPage,"records");
        List<Dish> records = pageinfo.getRecords();
        List<DishDto> list = records.stream().map((menu) -> {//menu对应的是菜品对象

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(menu,dishDto);
            Long categoryId = menu.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();//获取分类名称
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }
    /*
    *回显
    * 查询菜品数据 select * from dish where id = ?
    * */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /*
    * 修改菜品数据
    * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /*
    * 删除数据
    * */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId,ids);
        dishService.remove(qw);
        LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
        qw1.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(qw1);
        return R.success("删除成功");
    }

    /*
    * 启用禁用
    * */
    @PostMapping("/status/{status}")
    public R<String> EnableWithDisable(@RequestParam List<Long> ids,@PathVariable Integer status){

        LambdaUpdateWrapper<Dish> lup = new LambdaUpdateWrapper<>();
        lup.set(Dish::getStatus,status);
        lup.in(Dish::getId,ids);
        boolean update = dishService.update(lup);
        if (update){
            return R.success("启用");
        }else {
            return R.error("禁用");
        }

    }

    /*
    * 根据分类id查询该分类下的所有菜品集合
    * */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());//先判断分类id不为空,在匹配id
        qw.eq(Dish::getStatus,1);//添加条件，查询状态为1（起售状态）的菜品
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(qw);
        List<DishDto> dishDtos = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //获取分类对象
            Category category = categoryService.getById(categoryId);
            //获取分类名称
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //获取当前的菜品id
            Long dishId = item.getId();
            //获取口味信息
            LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(qw1);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }

}
